<template>
  <div class="add-point-dialog">
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑商品' : '添加商品'"
      width="60%"
      @closed="closed"
    >
      <div class="dialog-content">
        <el-form
          ref="ruleFormRef"
          :model="form"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="标题" prop="title">
            <el-input v-model.trim="form.title" type="text" />
          </el-form-item>
          <el-form-item label="简介" prop="introduce">
            <el-input v-model.trim="form.introduce" type="text" />
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <Editor v-model="form.content" />
          </el-form-item>
          <el-form-item label="价格" prop="price">
            <el-input-number v-model="form.price" :min="0" />
          </el-form-item>
          <el-form-item label="数量" prop="inventory">
            <el-input-number v-model="form.inventory" :min="0" />
          </el-form-item>
          <el-form-item label="地址" prop="placeOfDelivery">
            <el-input v-model.trim="form.placeOfDelivery" type="text" />
          </el-form-item>
          <el-form-item label="图片">
            <el-upload
              v-model:file-list="fileList"
              action="#"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :http-request="httpRequest"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit" :loading="isLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="imgDialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Plus } from "@element-plus/icons-vue";
import Editor from "@/components/Editor/index.vue";
import { ref, watch, reactive, computed } from "vue";
import type {
  FormInstance,
  FormRules,
  UploadProps,
  UploadRequestOptions,
  UploadUserFile
} from "element-plus";
import { ElMessage } from "element-plus";
import { AddShop, ShopItem } from "@/api/shop/shop";
import { addShop, editItem } from "@/api/shop/index";
import { upload } from "@/utils/oss";

defineOptions({
  name: "addUser"
});
interface Props {
  modelValue: boolean;
  isEdit: boolean;
  info: ShopItem | null;
}
const props = defineProps<Props>();
const emits = defineEmits(["update:modelValue", "getList"]);
const dialogVisible = computed({
  get() {
    return props.modelValue;
  },
  set(newValue) {
    emits("update:modelValue", newValue);
  }
});

// 表单
const ruleFormRef = ref<FormInstance>();
const form = ref<AddShop>({
  title: "",
  introduce: "", //简介
  content: "", //内容
  price: 0, //价格
  inventory: 1, //库存
  placeOfDelivery: "", //发货地
  pictures: "[]"
});
// 文件处理
const fileList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref("");
const imgDialogVisible = ref(false);
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  form.value.pictures = JSON.stringify(getFileListUrl());
};

const handlePictureCardPreview: UploadProps["onPreview"] = uploadFile => {
  dialogImageUrl.value = uploadFile.url!;
  imgDialogVisible.value = true;
};
const httpRequest = async (options: UploadRequestOptions) => {
  const res = await upload(options.file, "shop");
  return Promise.resolve(res);
};
// 获取文件地址
const getFileListUrl = (): string[] => {
  return JSON.parse(props.info.pictures) || [];
};
// 表单回显
watch(
  () => props.info,
  () => {
    if (props.isEdit) {
      for (const key in form.value) {
        form.value[key] = props.info[key];
      }
      const picList = getFileListUrl();
      picList.forEach((el, index) => {
        fileList.value.push({ response: el, name: String(index), url: el });
      });
    }
  }
);
const rules = reactive<FormRules<typeof form>>({
  title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
  introduce: [{ required: true, message: "简介不能为空", trigger: "blur" }],
  placeOfDelivery: [
    { required: true, message: "地址不能为空", trigger: "blur" }
  ]
});
const closed = () => {
  form.value = {
    title: "",
    introduce: "", //简介
    content: "", //内容
    price: 0, //价格
    inventory: 1, //库存
    placeOfDelivery: "", //发货地
    pictures: "[]"
  };
  fileList.value = [];
  ruleFormRef.value.clearValidate();
};
// 添加
const add = async () => {
  const pictures = JSON.stringify(fileList.value.map(el => el.response));
  const res = await addShop({
    ...form.value,
    pictures
  });
  return res;
};
// 编辑
const edit = async () => {
  const pictures = JSON.stringify(fileList.value.map(el => el.response));
  const res = await editItem({ ...form.value, id: props.info.id, pictures });
  return res;
};
// 提交
const isLoading = ref(false);
const submit = () => {
  ruleFormRef.value.validate(async valida => {
    if (valida) {
      isLoading.value = true;
      const res = props.isEdit ? await edit() : await add();
      isLoading.value = false;
      if (res.code === 200) {
        dialogVisible.value = false;
        ElMessage.success(`${props.isEdit ? "编辑" : "添加"}成功`);
        emits("getList");
      }
    }
  });
};
</script>
<style lang="scss" scoped>
:deep(.el-form-item__label) {
  font-weight: 700;
}
</style>
